/*
 * Inspector.java
 *
 * Created on June 13, 2007, 9:58 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package sbc.jms;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EnumMap;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import sbc.fabrik.model.Employee;
import sbc.fabrik.model.Feature;
import sbc.fabrik.model.Sensor;

/**
 *
 * @author goran
 */
public class Inspector extends Employee {
    
    private Feature feature = null;

    QueueConnectionFactory  queueConnectionFactory = null;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    Queue queue = null;
   
    /** Creates a new instance of Inspector */
    public Inspector(int id) {
        super(id);
                Context jndiContext = null;
        
        
        try {
            Properties properties = new Properties();
            properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
            properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
            properties.put(Context.PROVIDER_URL, "localhost");
            
            jndiContext = new InitialContext(properties);
            
            queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("ConnectionFactory");
            queue = (Queue) jndiContext.lookup("queue/sbc");
            
        } catch (NamingException e) {System.out.println("JNDI lookup failed: " + e.toString());
        e.printStackTrace();
        System.exit(1);
        }

    }
    

    
    public void work() {
           try {
            ObjectMessage             message = null;
            
            
            queueConnection = queueConnectionFactory.createQueueConnection();
            QueueSession session = (QueueSession)  queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            String sensorQuery = "ModulType = '" + Sensor.class.getCanonicalName() + "'" 
                    + "AND " + getFeature().name() + "= false";
            //System.out.println(sensorQuery);
            QueueReceiver SensorSubscriber =  session.createReceiver(queue, sensorQuery);
            QueueSender SensorSender = session.createSender(queue);
            
            queueConnection.start();
            System.out.println("receiving...");
            
            
                ObjectMessage modul =  (ObjectMessage) SensorSubscriber.receive();
                //System.out.println(modul);
                //System.out.println(modul.getClass().getCanonicalName());
                Sensor sensor = (Sensor) modul.getObject();
                System.out.println(sensor);
                sensor.inspect(feature, new Employee(super.getId()));

                // send back sensor
                ObjectMessage outMsg = session.createObjectMessage();
                EnumMap<Feature, Employee> m = sensor.getFeaturesEmployees();
                boolean allDone = true;                
                for (Feature f : sensor.getFeatures()) {
                    if (m.get(f) != null) {
                        outMsg.setBooleanProperty(f.name(), true);
                    } else {
                        outMsg.setBooleanProperty(f.name(), false);
                        allDone = false;
                    }
                }
                if (allDone)
                    outMsg.setBooleanProperty("Inspected", true);
                
                 outMsg.setStringProperty("ModulType", sensor.getClass().getCanonicalName());
                 outMsg.setObject(sensor);
                //System.out.println("SENDING***************************" + outMsg);
                SensorSender.send(outMsg);
            
            
            
            
            System.out.println("**************************************************");
            
            
            
        } catch (Exception e) {
            System.out.println("Exception occurred: " +
                    e.toString());
            e.printStackTrace();
        } finally {
            if (queueConnection != null) {
                try {
                    queueConnection.close();
                } catch (JMSException e) {}
            }
        }
        
    }
    
    public static void main(String[] args) {
       InputStreamReader       inputStreamReader = null;
        char                    answer = '\0';
 
        Inspector spec = null;
        if (args.length == 2) {
            spec = new Inspector(Integer.parseInt(args[0]));    
            spec.setFeature(Feature.valueOf(args[1]));
        }
        else {
            System.out.println("Usage: java Inspector <id> <feature>");
            System.exit(1);
        }
        
        
        System.out.println("Inspector (" + spec.getId() + ") inspecting " + spec.getFeature().name());
        System.out.println("To end program, enter Q or q, then <return>");
        inputStreamReader = new InputStreamReader(System.in);
        while (!((answer == 'q') || (answer == 'Q'))) {
            spec.work();
        }
        try {
            answer = (char) inputStreamReader.read();
        } catch (IOException e) {
            System.out.println("I/O exception: "
                    + e.toString());
        }

    }

    
    public Feature getFeature() {
        return feature;
    }

    public void setFeature(Feature feature) {
        this.feature = feature;
    }
    
}
